package router

import (
	"apibe/grpc/rome/v1/router/handler"
	"apibe/grpc/rome/v1/share/crypt"
	"apibe/grpc/rome/v1/share/middler"
	"encoding/json"
	"github.com/gin-gonic/gin"
)

func ApiSelector(c *gin.Context) {
	action := c.Param("action")
	selector := c.Param("selector")
	result := handler.ApiSelectorHandler(action, selector)
	c.Set(middler.RESULT, result)
}

func ApiChangeStatus(c *gin.Context) {
	work := c.Param("work")
	action := c.Param("action")
	id := c.Param("id")
	claims := c.MustGet(middler.CLAIMS).(*crypt.CustomClaims)
	err := handler.ApiStatusHandler(work, action, id, claims)
	if err != nil {
		c.Set(middler.CODE, middler.ErrMgo)
		c.Set(middler.MSG, err.Error())
		return
	}
	c.Set(middler.RESULT, "SUCCESS")
}
func ApiCacheResponse(c *gin.Context) {
	action := c.Param("action")
	id := c.Param("id")
	result := handler.ApiCacheResponseHandler(action, id)
	c.Set(middler.RESULT, result)
}

func ApiExportPostman(c *gin.Context) {
	var in = struct {
		Name    string   `json:"name"`
		Url     string   `json:"url"`
		ApiName []string `json:"api_name"`
	}{}
	err := c.ShouldBindJSON(&in)
	if err != nil {
		_, _ = c.Writer.Write([]byte(err.Error()))
		return
	}
	token := c.Request.Header.Get("Authorization")
	postman, err := handler.ApiPostDownloadHandler(in.Name, in.Url, token, in.ApiName)
	if err != nil {
		_, _ = c.Writer.Write([]byte(err.Error()))
		return
	}
	bytes, _ := json.Marshal(postman)
	_, _ = c.Writer.Write(bytes)
}

func ApiGetWatch(c *gin.Context) {
	apiName := c.Param("api_name")
	watch, err := handler.ApiGetWatchHandler(apiName)
	if err != nil {
		c.Set(middler.CODE, middler.ErrReq)
		c.Set(middler.MSG, err.Error())
		return
	}
	c.Set(middler.RESULT, watch)
}
